<template>
	<div>
		<el-row>
			<el-col :span="24">
				<el-form :model="queryWhere" :inline="true">
					<el-form-item label="角色名称(模糊查询)">
						<el-input v-model="queryWhere.role_name"></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="initTableData">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="success" style="float: right;" @click="addDialog()">添加角色</el-button>
					</el-form-item>
				</el-form>

			</el-col>
		</el-row>

		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="queryWhere.currentPage" :page-sizes="[5,10, 15, 20, 30]" :page-size="pageInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.totalRecord">
		</el-pagination>

		<!-- 角色列表区域 -->
		<el-table :data="roleList" border stripe v-loading="loading">
			<el-table-column label="id" prop="role_id"></el-table-column>
			<el-table-column label="角色名称" prop="role_name"></el-table-column>
			<el-table-column label="角色描述" prop="role_desc"></el-table-column>
			<el-table-column label="操作" width="300">
				<template slot-scope="scope">
					<!-- 修改按钮 -->
					<el-button type="primary" icon="el-icon-edit" size="small" @click="editDialog(scope.row)">修改
					</el-button>
					<!-- 删除按钮 -->
					<el-button type="danger" icon="el-icon-delete" size="small" @click="delDialog(scope.row.role_id)">删除
					</el-button>
					<!-- 分配权限按钮 -->
					<el-button type="warning" icon="el-icon-key" size="small" @click="setDialog(scope.row)">分配权限
					</el-button>
				</template>

			</el-table-column>
		</el-table>

		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="queryWhere.currentPage" :page-sizes="[5,10, 15, 20, 30]" :page-size="pageInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.totalRecord">
		</el-pagination>

		<!-- 添加角色的对话框 -->
		<el-dialog :title="title" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
			<!-- 内容主体区域 -->
			<el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
				<el-form-item label="角色名" prop="role_name">
					<el-input v-model="addForm.role_name"></el-input>
				</el-form-item>
				<el-form-item label="角色描述" prop="role_desc">
					<el-input v-model="addForm.role_desc"></el-input>
				</el-form-item>
			</el-form>
			<!-- 底部区域 -->
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="addRole">确 定</el-button>
				<el-button @click="addDialogVisible = false">取 消</el-button>
			</span>
		</el-dialog>

		<!-- 分配权限的对话框 -->
		<el-dialog title="分配权限" :visible.sync="setDialogVisible" width="50%" @close="setDialogClosed">
			<!-- 树形控件 -->
			<el-tree :data="permissionList" :props="treeProps" show-checkbox node-key="permission_id" default-expand-all
				:default-checked-keys="defKeys" ref="treeRef"></el-tree>
			<span slot="footer" class="dialog-footer">
				<el-button @click="setDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="setPermission()">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		created:function(){
			this.access_token = window.sessionStorage.getItem("token");
		},
		data() {
			return {
				//记录token
				access_token: "",
				loading: true,
				queryWhere: {
					role_name: '',
					currentPage: 1,
					pageSize:5
				},
				pageInfo: {
					pageSize: 5,
					totalPage: 0,
					totalRecord: 0
				},
				//所有角色列表数据
				roleList: [],
				//设置权限的对话框显示与隐藏
				setDialogVisible: false,
				//指定角色的权限
				permissionList: [],
				//树形控件的属性绑定对象
				treeProps: {
					label: 'name',
					children: 'children'
				},
				//默认的选中的id值数组
				defKeys: [],
				//表单名称
				title: '',
				//当前即将分配角色的id
				roleId: '',
				roleFlag: false,
				//控制添加对话框的显示和隐藏
				addDialogVisible: false,
				// 登录表单的数据绑定对象
				addForm: {
					role_id: '',
					role_name: '',
					role_desc: ''
				},
				// 添加表单的验证规则
				addFormRules: {
					// 验证会员名是否合法
					role_name: [{
							required: true,
							message: '请输入角色名',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 16,
							message: '长度在 2 到 16 个字符',
							trigger: 'blur'
						}
					]
				}
			}
		},
		methods: {
			//避免走太快解决undefined问题
			doSetDialogVisible: function() {
				this.setDialogVisible = true;
			},
			//确认设置权限
			setPermission: async function() {
				const keys = this.$refs.treeRef.getCheckedKeys();
				console.log('keys', keys);
				//把数字改成字符串
				const pids = keys.join(',');
				console.log('pids', pids)

				//发生请求删除角色信息
				let _this = this;
				let url = "/api/mall/RoleServlet.do?method=confirmAssignPermission";

				await this.$http.get(url, {
					params: {
						roleId: this.roleId,
						pids: pids
					}
				}).then(function(response) {
					console.log("setPermission服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.$message({
							message: response.data.msg,
							type: 'success'
						});
						
						
					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});
				})

				this.setDialogVisible = false
				this.initTableData(); //重新查数据库。

			},
			//监听分配权限对话框的关闭
			setDialogClosed() {
				this.defKeys.splice(0, this.defKeys.length)
				console.log('setDialogClosed之后', this.defKeys)
			},
			setDialog: async function(role) {

				await this.doSetDialogVisible();

				console.log('setDialogf方法执行了')
				this.roleId = role.role_id
				//获取该角色的权限
				let _this = this;

				console.log('this.permissionList', this.permissionList)

				//递归获取二级权限id
				for (let i = 0; i < role.permissions.length; i++) {
					//arr.push(node[i].permission_id)
					for (let j = 0; j < role.permissions[i].children.length; j++) {
						this.defKeys.push(role.permissions[i].children[j].permission_id)
					}
				}
				this.$refs.treeRef.setCheckedKeys(this.defKeys, false);
				//this.getLeafKeys(role.permissions, this.defKeys)
				console.log('递归获取二级权限之后 ', this.defKeys);


			},
			//通过递归的形式，获取角色的所有二级权限id,并保存到defKeys数组中 无用
			getLeafKeys(node, arr) {
				for (let i = 0; i < node.length; i++) {
					//arr.push(node[i].permission_id)
					for (let j = 0; j < node[i].children.length; j++) {
						arr.push(node[i].children[j].permission_id)
					}
				}
				console.log('arr', arr);
				console.log('this.defKeys', this.defKeys)
			},
			//删除角色 真的删除
			delDialog: async function(roleId) {

				//弹框询问是否删除
				const confirmResult = await this.$confirm('是否删除该角色', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(function(error) {
					console.log(error);
				})

				if (confirmResult != 'confirm') {
					return this.$message.info('已取消删除')
				}

				//发生请求删除角色信息
				let _this = this;
				let url = "/api/mall/RoleServlet.do?method=deleteRoleById";

				await this.$http.get(url, {
					params: {
						roleId: roleId,
					}
				}).then(function(response) {
					console.log("address服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.$message({
							message: response.data.msg,
							type: 'success'
						});
					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});
				})
				this.loading = true;
				this.initTableData(); //重新查数据库。
			},

			// 点击修改按钮
			editDialog(roleInfo) {
				//给表单赋值
				this.title = '更新角色'
				this.roleFlag = true
				//浅拷贝
				//this.addForm = roleInfo
				//使用深拷贝
				this.addForm = JSON.parse(JSON.stringify(roleInfo))
				this.addDialogVisible = true
			},
			// 点击新增按钮
			addDialog() {
				//给表单赋值
				this.title = '添加角色'
				this.roleFlag = false
				this.addForm = {}
				this.addDialogVisible = true
			},
			//添加和修改共用
			addRole: function() {
				let _this = this;
				//判断是新增还是修改
				let url = '';
				if (this.addForm.role_id != null) {
					url = '/api/mall/RoleServlet.do?method=updateRoleById'
				} else {
					url = '/api/mall/RoleServlet.do?method=saveRole'
				}

				this.$refs.addFormRef.validate(function(valid, object) {
					if (!valid) {
						return;
					}
					_this.$http.get(url, {
						params: _this.addForm
					}).then(function(response) {
						console.log("orderdetail服务端返回的数据为:", response);
						if (response.data.code == 0) {
							_this.$message({
								message: response.data.msg,
								type: 'success'
							});
						} else {
							_this.$message(response.data.msg)
						}
					}).catch(function(error) {
						console.log("服务端产生异常为:", error);
						_this.$notify({
							title: '提示',
							message: "系统错误:" + error,
							duration: 2000
						});
					})

					_this.addDialogVisible = false
					//重置表单
					_this.$refs.addFormRef.resetFields()

					_this.loading = true;
					_this.initTableData();

				})
			},
			addDialogClosed() {
				this.$refs.addFormRef.resetFields()
			},
			initTableData: function() {
				let _this = this;
				let url = "/api/mall/RoleServlet.do?method=queryAllRole&access_token="+this.access_token;

				this.$http.get(url, {
					params: _this.queryWhere
				}).then(function(response) {
					console.log("服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.queryWhere.currentPage = response.data.data.currentPage;
						_this.pageInfo.totalPage = response.data.data.totalPage;
						_this.pageInfo.totalRecord = response.data.data.totalRecord;
						_this.pageInfo.pageSize = response.data.data.pageSize;
						_this.roleList = response.data.data.data;

						_this.loading = false;
					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});

				})
			},
			handleSizeChange: function(pageSize) {
				//alert("修改了每页显示的记录数",val);
				//console.log("修改了每页显示的记录数",val)
				this.loading = true;
				this.queryWhere.pageSize= pageSize;
				this.initTableData(); //重新查数据库。。
			},
			handleCurrentChange: function(curPage) {
				this.loading = true;
				this.queryWhere.currentPage = curPage; //当页页
				this.initTableData(); //重新查数据库。。
			}
		},
		mounted() {
			this.initTableData();
			let _this = this;
			let url = "/api/mall/RoleServlet.do?method=getPermissionList&access_token="+this.access_token;
			this.$http.get(url).then(function(response) {
				console.log("setDialog服务端返回的数据为:", response);
				if (response.data.code == 0) {
					_this.permissionList = response.data.data;
					console.log('_this.permissionList', _this.permissionList);
				} else {
					_this.$message(response.data.msg)
				}

			}).catch(function(error) {
				console.log("服务端产生异常为:", error);
				_this.$notify({
					title: '提示',
					message: "系统错误:" + error,
					duration: 2000
				});
			})


		},

	}
</script>

<style>
	.el-tag {
		margin: 7px;
	}

	.bdtop {
		border-top: 1px solid #eee;
	}

	.bdbottom {
		border-bottom: 1px solid #eee;
	}

	.vcenter {
		display: flex;
		align-items: center;
	}
</style>
